const messagesService = require('../service/messages-service')

class MessagesController {
  // 分页查询
  async getMessages (ctx, next) {
    const { limit, offset } = ctx.request.query
    if (!limit) {
      const result = await messagesService.list()
      return ctx.body = result
    }
    const start = Number(offset)
    const end = Number(limit) + Number(offset)
    const [result, total] = await Promise.all([messagesService.getMessageList(start, end), messagesService.getDataNum()])
    ctx.body = {
      msgs: result,
      total
    }
  }
  
  // 设置留言信息
  async setMessage (ctx, next) {
    const { msg, timestamp } = ctx.request.body
    const result = await messagesService.setMessage(msg, timestamp)
    ctx.body = result
  }

  // 删除留言
  async removeMessage(ctx, next) {
    const { messageId } = ctx.params
    const result = await messagesService.remove(messageId)
    ctx.body = result
  }
}

module.exports = new MessagesController()